package com.ruoyi.web.controller.distribution;

import cn.distribution.groupManager.entity.dao.GroupManagerDAO;
import cn.distribution.groupManager.service.GroupManagerService;
import cn.distribution.messagesManager.entity.dao.MessagesManagerDAO;
import cn.distribution.messagesManager.entity.vo.MessagesManagerVO;
import cn.distribution.messagesManager.service.MessagesManagerService;
import cn.distribution.personManager.entity.dao.PersonManagerDAO;
import cn.distribution.personManager.entity.vo.PersonExportVO;
import cn.distribution.personManager.entity.vo.PersonManagerVO;
import cn.distribution.personManager.entity.vo.personTemplateVO;
import cn.distribution.personManager.service.PersonManagerService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import javafx.scene.control.Alert;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhengminjie xiayujia
 */
@RestController
@RequestMapping("/distribution/personManager")
public class PersonManagerController extends BaseController {
    protected final Logger logger = LoggerFactory.getLogger(PersonManagerController.class);

    @Autowired
    private GroupManagerService groupManagerService;

    @Autowired
    private PersonManagerService personManagerService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private MessagesManagerService messagesManagerService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @GetMapping("/select")
    public TableDataInfo selectGroup(String userIdentity) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        startPage();
        List<GroupManagerDAO> result= this.groupManagerService.getGroupNameByIdentity("普通人",userId);
        logger.info(result.toString());
        return getDataTable(result);
    }

    @GetMapping("/search")
    public TableDataInfo getGroupList(Long groupId) {
        List<PersonManagerVO> personManagerVOList;
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        startPage();
        personManagerVOList= this.personManagerService.getListById(groupId,userId,"普通人");
        logger.info(personManagerVOList.toString());
        return getDataTable(personManagerVOList);
    }

    @GetMapping("/searchMI")
    public TableDataInfo searchPersonId(Long groupId) {
        List<PersonManagerVO> personManagerVOList;
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        startPage();
        personManagerVOList= this.personManagerService.searchMember(groupId, userId,"创建者");
        logger.info(personManagerVOList.toString());
        return getDataTable(personManagerVOList);
    }

    @PostMapping("/add")
    public AjaxResult addMember(@RequestBody Map<String,Object> datas){
        System.out.println(datas);
        MessagesManagerVO messagesManagerVO = new MessagesManagerVO();
        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
        Long num = Long.parseLong(datas.get("groupNum").toString().trim());
        System.out.println(num);
        Long groupid=this.groupManagerService.getIdByNum(num);
        String name= (String) datas.get("userName");  //用户名
        System.out.println(name);
        PersonManagerDAO personManagerDAO = new PersonManagerDAO();
        long groupId = this.groupManagerService.getIdByNum(num);
        GroupManagerDAO groupManagerDAO = this.groupManagerService.getById(groupId);
        try {
            Long userId=this.iSysUserService.selectUserByUserName(name).getUserId();
                personManagerDAO.setGroupId(groupId);
                personManagerDAO.setGroupNum(num);
                personManagerDAO.setUserId(userId);
                personManagerDAO.setGroupUserName(name);
                personManagerDAO.setUserIdentity("普通人");
                personManagerDAO.setDataDistribution(false);
                this.personManagerService.save(personManagerDAO);
                messagesManagerDAO.setMessageType(Long.parseLong("3"));
                messagesManagerDAO.setMessageContent("你有一条入群消息");
                messagesManagerDAO.setContent("欢迎你加入" + this.groupManagerService.getNameById(groupId) + "群");
                messagesManagerDAO.setState(false);
                messagesManagerDAO.setCreateTime(new Date());
                this.messagesManagerService.save(messagesManagerDAO);
                return AjaxResult.success("添加成员成功");
        }catch (Exception e)
        {
            if(personManagerDAO.getGroupUserName()==name)
            {
                System.out.println("该用户成员已存在该群组中，请重新输入");
                return AjaxResult.success("该用户成员已存在该群组中");
            }
            else{
                System.out.println("用户不存在");
                return AjaxResult.success("用户不存在");
            }
        }
    }

    @PostMapping("/delete")
    public AjaxResult deleteMember(@RequestBody Map<String,Object> datas){
        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
        System.out.println(datas);
        Long groupId=Long.parseLong(datas.get("groupId").toString().trim());
        //List<String> userName= (List<String>) datas.get("username");
        JSONArray array1= JSONArray.parseArray(JSON.toJSONString(datas.get("userId")));
        List<Long> userId= JSONObject.parseArray(array1.toString(),Long.class);
        for(Long Id:userId) {
                System.out.println(Id);
                messagesManagerDAO.setUserName(iSysUserService.selectUserById(Id).getUserName());
                messagesManagerDAO.setMessageType(Long.parseLong("3"));
                messagesManagerDAO.setMessageContent("你有一条被删消息");
                messagesManagerDAO.setContent("很可惜你与" + this.groupManagerService.getNameById(groupId) + "群无缘");
                messagesManagerDAO.setState(false);
                messagesManagerDAO.setCreateTime(new Date());
                this.messagesManagerService.save(messagesManagerDAO);
                this.personManagerService.deleteMember(groupId, Id);
        }
        return AjaxResult.success("删除成员成功");
    }

    @PostMapping("/powerConfig")
    public AjaxResult configurePower(@RequestBody Map<String,Object> datas){
//        MessagesManagerDAO messagesManagerDAO = new MessagesManagerDAO();
        Long useridConfirm = SecurityUtils.getLoginUser().getUser().getUserId();
        System.out.println(useridConfirm);
        Long groupId=Long.parseLong(datas.get("groupId").toString().trim());
        Long groupNum=this.personManagerService.getNumById(groupId);
        System.out.println(groupNum);
        System.out.println(this.personManagerService.getIdentityByNum(groupNum,useridConfirm));
        String confirm=this.personManagerService.getIdentityByNum(groupNum,useridConfirm).trim();
        String con="创建者";
        if(confirm.equals(con))
        {
            Long userId=Long.parseLong(datas.get("userId").toString().trim());
            String userIdentity= (String) datas.get("userIdentity");
            Boolean dataDistr= Boolean.valueOf(datas.get("dataDistribution").toString().trim());
            this.personManagerService.updateIdentiDistri(groupId,userId,userIdentity,dataDistr);
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            if(dataDistr) {
                Long roleIds[] = {Long.parseLong("100")};
                sysUser.setRoleIds(roleIds);
            }else{
                Long roleIds[] = {Long.parseLong("101")};
                sysUser.setRoleIds(roleIds);
            }
            this.sysUserService.updateUser(sysUser);
            return AjaxResult.success("权限配置成功");
        }
        else{

            return AjaxResult.success("不是创建者");
        }
    }

    @PostMapping("/infoModify")
    public AjaxResult modifyInfo(@RequestBody Map<String,Object> datas){
        Long useridConfirm = SecurityUtils.getLoginUser().getUser().getUserId();
        Long groupId=Long.parseLong(datas.get("groupId").toString().trim());
        Long groupNum=this.personManagerService.getNumById(groupId);
        System.out.println(this.personManagerService.getIdentityByNum(groupNum,useridConfirm));
        String confirm=this.personManagerService.getIdentityByNum(groupNum,useridConfirm).trim();
        String con="创建者";
        if(confirm.equals(con))
        {

            Long userId=Long.parseLong(datas.get("userId").toString().trim());
            Long userNumber;
            String groupUserName;
            if(datas.get("userNumber").toString()=="")
            {
                userNumber=null;
            }
            else {
                userNumber=Long.parseLong(datas.get("userNumber").toString().trim());
            }
            if( datas.get("groupUserName")=="")
            {
                groupUserName=null;
            }
            else {
                groupUserName=(String) datas.get("groupUserName");
            }
            System.out.println(groupUserName);
            System.out.println(userNumber);
            this.personManagerService.updateInfo(groupId,userId,groupUserName,userNumber);
            return AjaxResult.success("信息修改成功");
        }
        else{
            return AjaxResult.success("不是创建者");
        }
    }

    @Log(title = "导入成员名单", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(@RequestParam("groupid")String groupid, MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<personTemplateVO> util = new ExcelUtil<personTemplateVO>(personTemplateVO.class);
        List<personTemplateVO> personTemplateVOList = util.importEasyExcel(file.getInputStream());
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        SysUser user = new SysUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        PersonManagerDAO personManagerDAO = new PersonManagerDAO();
        for(personTemplateVO personTemplateVO:personTemplateVOList){
            SysUser sysUser = sysUserMapper.selectUserByUserName(personTemplateVO.getUserName());
            try {
                //如果用户名不存在就注册 密码为用户名
                if (StringUtils.isNull(sysUser)) {
                    Long roleIds[] = {Long.parseLong("101")};
                    user.setNickName(personTemplateVO.getNickName());
                    user.setUserName(personTemplateVO.getUserName());
                    user.setPassword(SecurityUtils.encryptPassword(personTemplateVO.getUserName()));
                    user.setDeptId(Long.parseLong("200"));
                    user.setRemark("用户");
                    user.setRoleIds(roleIds);
                    user.setCreateBy(userName);
                    this.iSysUserService.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + personTemplateVO.getUserName() + " 导入成功");
                } else if (updateSupport) {
                    // 如果有变动 用户昵称更新
                    sysUser.setNickName(personTemplateVO.getNickName());
                    sysUser.setUpdateBy(userName);
                    this.iSysUserService.updateUser(sysUser);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + personTemplateVO.getUserName() + " 更新成功");
                }
                if(this.personManagerService.getIfExist(Long.valueOf(groupid),sysUserMapper.selectUserByUserName(personTemplateVO.getUserName()).getUserId())!=0){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + personTemplateVO.getUserName() + " 已存在在" + this.groupManagerService.getById(groupid).getGroupName() + "群");
                }
                else {
                    // 把该用户加入到该群中
                    personManagerDAO.setGroupId(Long.valueOf(groupid));
                    personManagerDAO.setGroupNum(groupManagerService.getById(personManagerDAO.getGroupId()).getGroupNum());
                    personManagerDAO.setUserId(sysUserMapper.selectUserByUserName(personTemplateVO.getUserName()).getUserId());
                    personManagerDAO.setUserIdentity("普通人");
                    personManagerDAO.setGroupUserName(personTemplateVO.getGroupUserName());
                    personManagerDAO.setUserNumber(personTemplateVO.getUserNumber());
                    personManagerDAO.setDataDistribution(false);
                    this.personManagerService.save(personManagerDAO);
                }
            }
            catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                logger.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，有部分导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return AjaxResult.success(successMsg);
    }

    /*  下载用户导入模板  */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<personTemplateVO> util = new ExcelUtil<personTemplateVO>(personTemplateVO.class);
        return util.exportEasyExcel(null,"导入成员名单模板");
    }

    @Log(title = "成员名单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Long groupId)
    {
        List<PersonExportVO> list = personManagerService.exportMember(groupId);
        ExcelUtil<PersonExportVO> util = new ExcelUtil<PersonExportVO>(PersonExportVO.class);
        return util.exportEasyExcel(list, "成员名单");
    }
}
